<!-- 组织管理列表 -->
<template>
  <div class="organ_list">
    <div class="organ_list_title">
      <div class="flex flex-vertical-center">
        <h2 style="text-align: left">{{ checkNodeTitle }}</h2>
        <p style="margin-left: 20px">{{ userIds.length }}人职位状态与人员状态不符</p>
        <Button
          style="margin-left: 10px; color: #2d8cf0; cursor: pointer"
          @click="viewUNPerson"
          type="text"
          v-if="userIds.length">
          查看明细
        </Button>
      </div>
      <div>
        <Button
          type="info"
          class="operate-btn"
          @click="batchDisabledFun"
          v-if="listFlag && unlocking('0201050000')">
          批量禁用
        </Button>
        <Button
          type="info"
          class="operate-btn"
          @click="onAddPerson"
          v-if="listFlag && unlocking('0201050000')">
          添加人员
        </Button>
        <Button
          type="info"
          class="operate-btn"
          @click="onEditPerson"
          v-if="listFlag && unlocking('0201060000')">
          调整人员所属
        </Button>
        <Button
          type="info"
          class="operate-btn"
          @click="disabledFun"
          v-if="listFlag && unlocking('0201030000')">
          禁用人员
        </Button>
        <Button
          type="success"
          class="operate-btn"
          @click="assignRoleFun"
          v-if="listFlag && unlocking('0201010000')">
          角色分配
        </Button>
        <Button type="info" class="operate-btn" @click="onExport" v-if="listFlag && unlocking('0201080000')">
          导出
        </Button>
        <Button
          type="info"
          class="operate-btn"
          @click="onExportLog"
          v-if="listFlag && unlocking('0201080000')">
          导出记录
        </Button>
      </div>
    </div>
    <div class="syBtn" v-if="!isBusinessFlag && notOrgNum > 0 && unlocking('0201070000')">
      <span>
        <Icon type="ios-alert" size="20" color="#999" />
        提示：当前有{{ notOrgNum }}个人员无归属业务组织
        <em @click="onCheckNotOrg">立即查看</em>
      </span>
    </div>
    <dt-grid ref="table" :page="pageData" :onFetch="onFetch" :select="select" />
    <assign-role ref="assignRole" @success="onSuccess"></assign-role>
    <change-log ref="changeLog"></change-log>
    <!-- 编辑人员 -->
    <dt-modal-edit
      ref="addCreate"
      title="编辑人员"
      :label-width="100"
      okText="确定"
      :width="80"
      @cancelData="modalCancel"
      @ok="addSave">
      <Tabs v-model="TabVal" type="card" @on-click="tabValChange">
        <TabPane label="人员信息" name="name1">
          <staff-info
            ref="staffInfo"
            v-if="addCreateFlag"
            :messInfo="messInfo"
            @onOperate="addSave"></staff-info>
        </TabPane>
        <TabPane label="前台角色" name="name2">
          <foreground-role ref="foregroundRole" v-if="addCreateFlag" :messInfo="messInfo"></foreground-role>
        </TabPane>
        <TabPane label="后台角色" name="name3">
          <back-role ref="backRole" :messInfo="messInfo" v-if="addCreateFlag"></back-role>
        </TabPane>
        <TabPane label="操作记录" name="name4">
          <dt-grid ref="table1" page :onFetch="onFetch1" :height="400" />
        </TabPane>
      </Tabs>
    </dt-modal-edit>
    <import-modal ref="importModal" @success="onImport"></import-modal>

    <export-log ref="exportLog" />
    <batch-disabled-modal ref="batchDisabledModal" @success="onSuccess" />
    <!--复制密码-->
    <dt-modal-edit
      ref="copyPwd"
      title="密码重置已重置"
      okText="复制密码"
      cancelText="关闭"
      @ok="copyPwdFun"
      :transfer="true">
      <p>
        {{ messInfo.name + '(' + messInfo.workNo + ')' }}的登录密码已重置为：
        <span style="color: #d9001b">{{ passwordText }}</span>
      </p>
    </dt-modal-edit>
  </div>
</template>

<script>
  import staffInfo from './compenent/staffInfo.vue'
  import importModal from './compenent/import-modal.vue'
  import foregroundRole from './compenent/foregroundRole.vue'
  import backRole from './compenent/backRole.vue'
  import assignRole from './compenent/assignRole.vue'
  import changeLog from './compenent/changeLog.vue'
  import exportLog from './compenent/export-log.vue'
  import columnOpt from './opt/columnOpt'
  import organApi from '@/biz/backStage/organizationManagement'
  import rolesOpt from '@/biz/option/roles.js'
  import roleMgr from '@/biz/role/role'
  import userMgr from '@/biz/user'
  import orgMgr from '@/biz/organizationManagement/organizationManagement'
  import operationMgr from '@/biz/operationLog/operationLog'
  import batchDisabledModal from './compenent/batchDisabledModal.vue'

  import operationColumn from './opt/operationColumn'
  export default {
    components: {
      assignRole,
      staffInfo,
      foregroundRole,
      backRole,
      changeLog,
      importModal,
      exportLog,
      batchDisabledModal
    },
    props: ['checkNodeTitle'],
    data() {
      return {
        listFlag: true,
        messInfo: '',
        addCreateFlag: false,
        TabVal: 'name1',
        orgCheck: {},
        select: {
          change: (e) => {
            this.onSelectChange(e)
          }
        },
        selectionList: [],
        editEmployeeMess: {
          roleIds: []
        },
        roleList: [],
        pageData: {
          current: 1
        },
        notOrgNum: 0,
        notDtOrg: false,
        isBusinessFlag: true,
        userIds: [],
        search: {},
        params: null,
        passwordText: ''
      }
    },
    methods: {
      logPageExport() {
        operationMgr.logPageExport(this.params)
      },
      // 查看异常人员
      viewUNPerson() {
        this.$refs.table.init(this, new columnOpt(this), {
          ownerText: '异常人员'
        })
        this.$refs.table.fetch()
        this.$refs.table.fixHeight()
      },
      tabValChange(val) {
        if (val == 'name4') {
          this.$refs.table1.init(this, new operationColumn(this))
          this.$refs.table1.fetch()
        }
      },
      onFetch1(data) {
        let params = {
          ...data,
          logModule: 'M_1',
          userId: this.messInfo.userId
        }
        this.params = params
        return operationMgr.logPage(params).then((res) => {
          return res
        })
      },

      addSave(resetPwd) {
        let reg1 = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
        if (this.$refs.staffInfo.info.phone && !reg1.test(this.$refs.staffInfo.info.phone)) {
          this.$Message.warning('请输入正确的手机号')
          return false
        }
        let usUserAuthList = []
        const res2 = this.$refs.backRole.roleData.some((item) => {
          return item.roleVO.id == ''
        })
        if (res2) {
          this.$Message.warning('角色不能为空')
          return false
        }
        const res3 = this.$refs.backRole.roleData.some((item) => {
          return item.permissionIds.length < 1
        })
        if (res3) {
          this.$Message.warning('功能权限不能为空')
          return false
        }

        const res1 = this.$refs.backRole.roleData.some((item) => {
          return item.orgList.length < 1
        })
        if (res1) {
          this.$Message.warning('组织不能为空')
          return false
        }
        this.$refs.backRole.roleData.forEach((item) => {
          let buildingIds = []
          item.buildingList.forEach((buildItem) => {
            buildingIds.push(buildItem.id)
          })
          let orgIds = []
          item.orgList.forEach((orgItem) => {
            orgIds.push(orgItem.id)
          })

          usUserAuthList.push({
            buildingIds: buildingIds.join(','),
            id: item.id,
            orgIds: orgIds.join(','),
            permissionIds: item.permissionIds.join(','),

            roleId: item.roleVO.id,
            roleName: item.roleVO.name,
            userId: this.messInfo.userId,

            orgSopBinding: item.orgSopBindingVO,
            delOrgSopBinding: item.delOrgSopBinding
          })
        })

        let params = {
          password: this.$refs.staffInfo.info.password,
          phone: this.$refs.staffInfo.info.phone,
          userId: this.messInfo.userId,
          usUserAuthList: usUserAuthList,
          createId: userMgr.info().userId
        }
        roleMgr.editUser(params).then((res) => {
          this.$Message.success('编辑成功。')
          this.passwordText = this.$refs.staffInfo.info.password
          if (resetPwd == true) {
            this.$refs.copyPwd.show()
          }
          this.$refs.staffInfo && this.$refs.staffInfo.successFun()
          this.$refs.addCreate.hide()
          this.onSuccess()
          this.$emit('updateOrg')
        })
      },
      copyPwdFun() {
        const aux = document.createElement('input')
        aux.setAttribute('value', this.passwordText)
        document.body.appendChild(aux)
        aux.select()
        document.execCommand('copy')
        document.body.removeChild(aux)
        this.$Message.success('复制成功')
      },
      //编辑
      onEdit(mess) {
        roleMgr.getUserCompile({ userId: mess.userId }).then((res) => {
          this.messInfo = mess
          this.addCreateFlag = true
          this.$refs.addCreate.show()
          this.messInfo.jyCompileStr = res.jyCompileStr
          this.messInfo.dtCompileStr = res.dtCompileStr
        })
      },
      modalCancel() {
        this.TabVal = 'name1'
        this.addCreateFlag = false
      },

      listByRoles() {
        rolesOpt.listByRoles().then((res) => {
          this.roleList = res
        })
      },
      // 切换组织
      checkOrgFun(type, data, notDtOrg = false) {
        this.listType = type
        this.orgCheck = data
        this.isBusinessFlag = type == 'business' ? true : false
        if (!this.isBusinessFlag) {
          orgMgr.getNotOrgCount(this.orgCheck.orgId).then((res) => {
            this.notOrgNum = res
          })
        }
        this.notDtOrg = notDtOrg
        this.pageData.current = 1
        this.$refs.table.clearFilter()
        this.$refs.table.fetch()

        this.listFlag = false
        setTimeout(() => {
          this.listFlag = true
        }, 100)
      },
      //角色分配
      assignRoleFun() {
        if (this.selectionList.length < 1) return this.$Message.error('请选择员工')
        this.editEmployeeMess.roleIds = []
        this.$refs.assignRole.show(this.selectionList)
      },
      //批量禁用上传表格
      batchDisabledFun() {
        this.$refs.batchDisabledModal.show()
      },
      // 批量禁用人员
      disabledFun() {
        if (!this.selectionList.length) return this.$Message.error('请先选择您要禁用的人员！')
        let disabledName = this.selectionList.map((item) => {
          return item.name
        })
        let params = {
          userIds: this.selectionList.map((item) => {
            return item.userId
          }),
          validate: 2,
          disableMsg: ''
        }
        this.$Modal.confirm({
          title: '禁用人员',
          render: (h) => {
            return h('div', [
              h('p', { style: { marginBottom: '10px' } }, `请确认,您要禁用${disabledName.join(',')}`),
              h('Input', {
                props: {
                  size: 'default',
                  placeholder: '请填写禁用原因'
                },
                on: {
                  'on-change': (event) => {
                    params.disableMsg = event.target.value
                  }
                }
              })
            ])
          },
          onOk: () => {
            organApi.validateUser(params).then((res) => {
              this.$Message.info('禁用成功。')
              this.onSuccess()
            })
          }
        })
      },
      //单个禁用
      openAuthority(mess) {
        let { userId, validate, name } = mess
        let disableMsg = ''
        this.$Modal.confirm({
          title: `${validate == '1' ? '禁用' : '启用'}人员`,
          render: (h) => {
            return h('div', [
              h(
                'p',
                { style: { marginBottom: '10px' } },
                `请确认,您要${validate == '1' ? '禁用' : '启用'}该员工！`
              ),
              h('Input', {
                props: {
                  size: 'default',
                  placeholder: '请填写禁用原因'
                },
                style: {
                  display: validate == '1' ? 'block' : 'none'
                },
                on: {
                  'on-change': (event) => {
                    disableMsg = event.target.value
                  }
                }
              })
            ])
          },
          onOk: () => {
            organApi
              .validateUser({
                userIds: [userId],
                validate: validate == '1' ? '2' : '1',
                disableMsg: disableMsg
              })
              .then((res) => {
                this.$Message.success(`${name}员工已被${validate == '1' ? '禁用' : '启用'}`)
                this.onSuccess()
              })
          }
        })
      },
      onExport() {
        organApi.exportOrgUsers(this.search)
      },
      onExportLog() {
        this.$refs.exportLog.show()
      },
      onSuccess() {
        this.$refs.table.fetch()
      },
      async onFetch(data) {
        data.roleId = this.$dt.userInfo().role.roleId
        data.userId = this.$dt.userInfo().userId
        data.flag = this.isBusinessFlag
        data.orgId = this.orgCheck.orgId
        data.departmentId = this.orgCheck.departmentId
        data.notDtOrg = this.notDtOrg
        // 角色筛选传中文
        if (data.role) {
          let roleName = []
          data.role.forEach((item) => {
            roleName.push(this.roleList.filter((ele) => ele.roleId == item)[0].roleName)
          })
          data.role = roleName.toString()
        }
        // 获取职位状态与人员状态不符
        await this.getPositionStatusUserIds(data)

        // 异常人员
        data.userIds = data.ownerText ? this.userIds : []
        this.selectionList = []
        this.search = data
        return organApi.getpeopleList(data)
      },
      //获取职位状态与人员状态不符
      getPositionStatusUserIds(params) {
        let countParams = {
          orgId: params.orgId
        }
        return organApi.getPositionStatusUserIds(countParams).then((res) => {
          this.userIds = res
        })
      },
      onSelectChange(e) {
        this.selectionList = e
      },

      //查看变更记录
      onChenckLog(mess) {
        this.$refs.changeLog.show(mess)
      },
      onCheckNotOrg() {
        this.checkOrgFun(this.listType, this.orgCheck, true)
      },
      onAddPerson() {
        this.$refs.importModal.show()
      },
      onEditPerson() {
        this.$router.push({
          name: 'adjustAffiliation'
        })
      },
      onImport() {
        setTimeout(() => {
          this.$refs.table.fetch()
        }, 1000)
      }
    },
    mounted() {
      this.$refs.table.init(this, new columnOpt(this))
      this.listByRoles()
    }
  }
</script>
<style lang="scss" scoped>
  .dao {
    display: flex;
    justify-content: end;
  }

  .organ_list {
    height: calc(100% - 20px);

    .organ_list_title {
      text-align: right;
      display: flex;
      justify-content: space-between;

      .operate-btn {
        margin-left: 5px;
      }
    }

    .syBtn {
      margin-top: 10px;

      span {
        line-height: 32px;

        background: rgba(254, 252, 236, 1);
        padding: 10px;

        em {
          font-style: normal;
          color: #19be6b;
          display: inline-block;
          margin-left: 5px;
          cursor: pointer;
        }
      }
    }
  }
</style>
